/**
 * Created by levy on 16/4/28.
 */
import MuiSlider from "../components/mui/MuiSlider.js";
import PullRefresh from "../components/mui/PullRefresh.js";
import Developing from "../components/Developing.js";
import {
    authModules
} from "../const/authModules";

(function (lf, r) {
    // let activity = '';
    let activity = false;
    
    let RC = r.createClass,
        doAction = lf.bridgeJs.doAction,
        queryAllDevice = lf.bridgeJs.queryAllDevice,
        sendControlCMD = lf.bridgeJs.sendControlCMD,
        ajax = lf.utils.ajax,
        log = lf.utils.log,
        imgUrl = lf.finger.imgUrl.finger,
        viewCode = lf.finger.viewCode.property,
        api = lf.finger.api,
        
        ajaxData = {}, //因为门禁，搞出了这个变量
        imgAndTextList = [
            //url不为空，则跳h5, pageTitle 是doAction的title
            {
                img: imgUrl + 'report.png',
                title: '报 事',
                titleClass: 'blue',
                url: 'report.html?flag=finger',
                pageTitle: '我要报事',
                viewCode: viewCode.report,
            }, {
                img: imgUrl + 'charges-query.png',
                title: '物业须知',
                titleClass: 'orange',
                url: 'property-instructions.html',
                pageTitle: '物业须知',
                viewCode: viewCode.chargesQuery,
            }, {
                img: imgUrl + 'property-intro.png',
                title: '智慧养老',
                titleClass: 'light-blue',
                viewCode: viewCode.introduction,
                url: 'index-oa.html',
                pageTitle: '小区简介',
            }, {
                img: imgUrl + 'phone.png',
                title: '客服电话',
                titleClass: 'green',
                viewCode: viewCode.customerService,
            },
        ];
    
    //TODO 以后有用,别删
    let scenes = [
        //{
        //    deviceName: '会客',
        //    type: 'scene',
        //    scene: 1,
        //},
        //{
        //    deviceName: '看书',
        //    type: 'scene',
        //    scene: 3,
        //},
        //{
        //    deviceName: '起床',
        //    type: 'scene',
        //    scene: 4,
        //},
        //{
        //    deviceName: '全开',
        //    type: 'scene',
        //    scene: 5,
        //},
        //{
        //    deviceName: '全关',
        //    type: 'scene',
        //    scene: 6,
        //},
        //{
        //    deviceName: '自定义',
        //    type: 'scene',
        //    scene: 7,
        //},
    ];
    
    let fixedIcon = [
        
        {
            type: 'fn',
            deviceName: '一键开门',
            deviceGlobalId: 'one-button-door',
            itemClass: 'device one-button-door purple',
            fn: (user) => lf.bridgeJs.getBleMsg(function (data) {
                
                if (data && data.deviceName) {
                    ajax({
                        type: 'GET',
                        data: {
                            guardDeviceSn: data.deviceName,
                        },
                        success: function (data) {
                            if (data.code == '200') {
                                ajax({
                                    type: 'POST',
                                    data: {
                                        guardDeviceId: data.data.id,
                                        householderId: user.id,
                                        householdType: user.householdType,
                                        openType: '0'
                                    },
                                    success: function (data) {
                                        if (data.code == '200') {
                                            alert('开门成功');
                                        } else {
                                            alert(data.desc);
                                        }
                                    }
                                }, lf.finger.api.door.open)
                                
                            } else {
                                alert(data.desc);
                            }
                        }
                    }, lf.finger.api.door.getDevice)
                    
                } else {
                    
                    ajax({
                        type: 'GET',
                        data: {
                            householderId: user.id,
                            householdType: user.householdType,
                            guardType: 'GUARD'
                        },
                        success: function (data) {
                            if (data.code == '200') {
                                var data = data.data
                                
                                if (data) {
                                    ajax({
                                        type: 'POST',
                                        data: {
                                            guardDeviceId: data.guardDeviceId,
                                            householderId: user.id,
                                            householdType: user.householdType,
                                            openType: '0'
                                        },
                                        success: function (data) {
                                            if (data.code == '200') {
                                                alert('开门成功');
                                            } else {
                                                alert(data.desc);
                                            }
                                        }
                                    }, lf.finger.api.door.open)
                                }
                            } else {
                                alert(data.desc)
                            }
                        }
                    }, lf.finger.api.door.getPrivilegeDefDevice)
                }
            })
            
        },
        // {
        //     type: 'scene',
        //     deviceName: '回 家',
        //     scene: 0,
        //     itemClass: 'iconfont back-home',
        // },
        //{
        //    type: 'scene',
        //    deviceName: '离 家',
        //    scene: 2,
        //    itemClass: 'iconfont off-home',
        //},
        {
            type: 'fn',
            deviceName: '密码开门',
            deviceGlobalId: 'code-door',
            itemClass: 'code-door',
            fn: (user) => ajax({
                type: 'GET',
                data: {
                    projectId: user.projectId,
                    houseNum: sessionStorage.houseNum,
                    householderId: user.id,
                    householdType: user.householdType,
                }
            }, api.door.getPasswd, function (data) {
                alert('密码是 ' + data);
            })
        }, {
            type: 'fn',
            deviceName: '扫码开门',
            deviceGlobalId: 'scan-code',
            itemClass: 'scan-code',
            fn: (user) => lf.bridgeJs.callAppHandler('scanQRCode', null, function (data) {
                var sentData = {
                    householderId: user.id,
                    householdType: user.householdType,
                };
                
                var url = lf.utils.getProtocol(data.result);
                
                ajax({
                    url: url,
                    type: 'POST',
                    data: sentData,
                    success: function (data) {
                        if (data.code == '200') {
                            debugAlert('success');
                            alert('开门成功');
                        } else
                            alert(data.desc);
                    },
                    error: function (xhr, errorType, error) {
                        alert(errorType)
                    }
                });
            }),
        }, {
            type: 'fn',
            deviceName: '一键呼援',
            deviceGlobalId: 'code-call',
            itemClass: 'icon-dianhua',
            fn: (user) => ajax({
                data: {
                    projectId: user.projectId,
                },
                success: (data) => {
                    lf.bridgeJs.dial(data.data.tel);
                    // lf.bridgeJs.dial('020-31134683');//列丰客服
                }
            }, lf.finger.api.property.getPhone)
        },
    
    ];
    /**
     * 默认渲染指点首页那些icon, 如果传rowRender，则使用自定义的渲染逻辑
     * 其实这个组件主要是解决一行有n个item的n不确定的问题。其本身是不渲染组件的
     * 这个组件不是无脑使用的，还是需要看一下代码。。。
     * rowRender: 具体的组件渲染写在父组件里(如果为空，渲染样式为指点首页的icon)
     * itemList: the items (not null)
     * count: the count of row items; default 4
     * addClass: add more class to the element, default 'flex-box'
     * TODO 现在只支持水平方向的布局, 这里跟指点首页的逻辑代码耦合太多了，很难解耦了。。。
     */
    var FlexBox = RC({
        getInitialState: function () {
            return {
                cmdsArray: [],
                deviceStates: [],
                types: [],
                fns: [], //函数数组
                houseNum: ''
            }
        },
        render: function () {
            var me = this,
                props = this.props,
                itemList = props.itemList || [],
                cls = props.addClass || '',
                count = props.count || 4,
                width = (100 / count || 25) + '%',
                array = [], //二维数组,用于分行
                rows = [];
            
            //为二维数组赋值
            for (var i = 0, len = itemList.length; i < len; i++) {
                //二维数组的下标
                var index = Math.floor(i / count);
                
                //undefined是不能进行操作的
                if (!array[index])
                    array[index] = [];
                array[index].push(itemList[i])
            }
            
            //width 不是必须的，
            //传它的意义在于：使用item固定子项目的宽度。如果要自动伸展，请让子项目带上.flex-item
            if (props.rowRender) {
                rows = array.map(function (row) {
                    return props.rowRender(row, width);
                });
            }
            //渲染finger-index 的icon
            //TODO 这个要抽出来，成为组件
            else {
                rows = array.map(function (row) {
                    var items = row.map(function (item) {
                        
                        //可以在render里直接改变state，不引起新一次渲染
                        //tap事件中要用到这些数据
                        item.actionCmds ?
                            me.state.cmdsArray.push(item.actionCmds) :
                            me.state.cmdsArray.push(item.scene);
                        
                        me.state.types.push(item.type); //后面大有用处
                        me.state.fns.push(item.fn);
                        
                        //TODO 目前没有
                        // me.state.deviceStates.push(item.lastReceiveCmd);
                        return (
                            <a key={item.deviceGlobalId} className="item circle-box" style={{width:width}}
                               data-cmd={item.cmd}>
                                <div className={"circle device " + (item.itemClass || '')}></div>
                                <span className="item-text">{item.deviceName.substr(0, 5)}</span>
                            </a>
                        )
                    });
                    
                    return (
                        <div className="flex-box-row">
                            {items}
                        </div>
                    )
                });
            }
            
            return (
                <div ref="flexBox" className={"flex-box " + cls}>
                    {rows}
                </div>
            )
        },
        componentDidMount: function () {
            
            //默认的渲染情况，绑定事件
            if (!this.props.rowRender) {
                let devices = r.findDOMNode(this.refs.flexBox).getElementsByTagName('a'),
                    cmdsArray = this.state.cmdsArray,
                    states = this.state.deviceStates,
                    types = this.state.types,
                    fns = this.state.fns;
                
                
                $.each(devices, function (i, device) {
                    let $me = $(this),
                        $circle = $me.find('.circle'),
                        actionCmds = cmdsArray[i] || [],
                        state = states[i] || {},
                        type = types[i] || '',
                        fn = fns[i] || '';
                    
                    
                    //显示设备激活状态
                    // if (cmds) {
                    //     $.each(cmds, function () {
                    //         if (this.cmdname && this.cmdname.indexOf('OPEN') > -1 && this.cmdname == state.cmdname) {
                    //             $circle.addClass('active');
                    //         }
                    //     });
                    // }
                    // log($me)
                    
                    //bind event
                    $me.on('tap', function (e) {
                        $circle.toggleClass('active');
                        
                        let cmd = '',
                            len = actionCmds.length;
                        
                        if (type != 'fn' && len > 0) {
                            if ($circle.hasClass('active')) {
                                //开
                                for (let i = 0; i < len; i++) {
                                    let actionCmd = actionCmds[i];
                                    if (actionCmd.action == 1) {
                                        cmd = actionCmd;
                                        break;
                                    }
                                }
                            } else {
                                //关
                                for (let i = 0; i < len; i++) {
                                    let actionCmd = actionCmds[i];
                                    if (actionCmd.action == 0) {
                                        cmd = actionCmd;
                                        break;
                                    }
                                }
                            }
                        }
                        if (!cmd) {
                            //场景 scene
                            if (type == 'scene') {
                                lf.bridgeJs.executeScene(cmds, function (data) {
                                    alert('scene ' + data);
                                });
                            }
                            //fixedIcon的自定义函数,发送ajax请求
                            else if (type == 'fn') {
                                fn && fn(ajaxData.user);
                            }
                            //自动恢复样式
                            setTimeout(function () {
                                $circle.toggleClass('active');
                            }, 500);
                        }
                        //普通设备
                        else
                            sendControlCMD(cmd);
                    })
                });
                
                lf.bridgeJs.connectBridge2RegisterHandler(function (bridge) {
                    
                    bridge.registerHandler("receiveDeviceCMD", function (data, cb) {
                        alert("cmd " + data);
                    });
                })
                
            }
        }
    });
    
    /**
     * 图文组件
     * img: not null
     * title: not null
     * detail: not null
     * titleClass: class of title
     * addClass: add more class to the element
     * tapFn: fire when component tapped
     */
    var ImgAndText = RC({
        render: function () {
            var props = this.props;
            //<p className="detail">{props.detail}</p>
            return (
                <div ref="imgText" className={"img-text-box " + (props.addClass || '')}>
                    <img className="img" src={props.img || lf.imgUrl.none}/>
                    <div className="text">
                        <p className={"title " + props.titleClass}>{props.title}</p>
                    </div>
                </div>
            )
        },
        componentDidMount: function () {
            var props = this.props,
                fn = props.tapFn;
            
            fn && r.findDOMNode(this.refs.imgText).addEventListener('tap', function (e) {
                fn(e);
            })
        }
    });
    
    
    /**
     * 首页不常变的内容。样式什么的，基本不可重用。。。
     */
    var StableContent = RC({
        
        render: function () {
            var props = this.props;
            return (
                <section ref="stable" className={"stable flex-box-row " + (props.addClass || '')}>
                    <div
                        className={"flex-item shopping " + (activity ? 'activity-mid-autumn' : '')}>
                        <header>商城</header>
                        <p className="box">新鲜优质 惠享生活</p>
                    </div>
                    <div className="flex-item flex-box-col">
                        <section className="flex-item living" ref="room">
                            <header>家居</header>
                            <p>简约方程式</p>
                        </section>
                        <section className="flex-item decoration tap">
                            <header>智慧门铃</header>
                            <p>安全 便捷</p>
                        </section>
                    </div>
                </section>
            )
        },
        componentDidMount() {
            var $stable = $(r.findDOMNode(this.refs.stable));
            var $room = $(r.findDOMNode(this.refs.room));

            $room.on('tap', function () {
                lf.appJs.doAction('../../zhwy-hybrid-om/index.html', '', 'noTitle');
            })
            
            $stable.find('.shopping').on('tap', () => {
                // if (!lf.prod || lf.utils.isLF()) {
                // lf.appJs.doAction('shopping-index.html', '指点');
                lf.appJs.doAction('shopping-index.html', '', 'noTitle');
                // } else
                //     this.props.showDeveloping();
            });
            
            $stable.find('.tap').on('tap', () => {
                this.props.showDeveloping();
            });
        }
    });
    
    /**
     * ***
     * 突发奇想，叫名字
     */
    
    
    var Snowball = RC({
        render: function () {
            return (
                <a ref="snowball" className="snowball iconfont more" draggable/>
            )
        },
        componentDidMount: function () {
            var $snowball = $(r.findDOMNode(this.refs.snowball)),
                $win = $(window),
                winWidth = $win.width(),
                winHeight = $win.height(),
                leftStop = 5,
                rightStop = winWidth - 60, //60 是 snowball的宽度
                topStop = 5,
                bottomStop = winHeight + 140,
                $scroll = '',
                scrollTop = 0;
            
            var flag = 0;
            //点击事件
            $snowball.on('tap', function (e) {
                doAction('finger-add.html', '指点部件');
            });
            
            //拖动事件
            $snowball.on('dragstart', function (e) {
                $snowball.addClass('active');
                
                $scroll = $('.mui-scroll');
                //前方高能！！！
                //格式 translate3d(0px, 191px, 0px) translateZ(0px)
                scrollTop = $scroll[0].style.webkitTransform.split(',', 2)[1].split('px')[0];
            });
            
            $snowball.on('drag', function (e) {
                var touch = e.detail.touches[0],
                    x = touch.clientX,
                    y = touch.clientY - scrollTop;
                
                //阻止越界
                if (x < leftStop)
                    x = leftStop;
                else if (x > rightStop)
                    x = rightStop;
                if (y < topStop)
                    y = topStop;
                else if (y > bottomStop)
                    y = bottomStop;
                
                $snowball.css({
                    left: x,
                    top: y
                })
            });
            
            $snowball.on('dragend', function (e) {
                var posix = $snowball.offset(),
                    x = rightStop;
                
                //移动到两侧
                if (posix.left <= winWidth / 2)
                    x = leftStop;
                
                $snowball.animate({
                    left: x
                });
                
                setTimeout(function () {
                    $snowball.removeClass('active');
                }, 500);
            });
            
        },
    });
    
    
    var Root = RC({
        getInitialState: function () {
            return {
                iconList: [],
                hasQueryDevice: false,
                noItem: 'default',
                homeImages: [], //图片相关属性
                imgOpenUrl: [],
                imageContentIds: [],
                titles: [], //图文的标题
                showDeveloping: '',
                isProperty: false,
                hasImg: true,
            }
        },
        componentWillMount: function () {
            var me = this;
            var user = {};
            
            lf.appJs.getUser(function (user) {
                sessionStorage.projectId = user.projectId;
                // debugAlert(user.projectId)
                console.log(user)
                me.ready(user)
            })

            lf.appJs.refresh(nextUser => {
                // debugAlert('refresh1');
                if(sessionStorage.projectId !== nextUser.projectId){
                    // debugAlert('refresh2');
                    sessionStorage.user = nextUser;
                    me.ready(nextUser);
                }
            })



            
            // //查询设备
            // queryAllDevice(function (deviceList) {
            //     me.setState({
            //         hasQueryDevice: true,
            //         iconList: me.renderIcon(fixedIcon.concat(deviceList))
            //     })
            // });
            
            // //广告图相关
            // lf.appJs.getUser(function (user) {
            //     // lf.appJs.refresh();
            //     user.custLoginVo && user.custLoginVo.authModules.map((type, i) => {
            //         if (type == authModules.module.property) {
            //             me.setState({
            //                 isProperty: true,
            //             })
            //         }
            //     })
            //     if (!user.custLoginVo) { //兼容3.0以前的老版本
            //         me.setState({
            //             isProperty: true,
            //         })
            //     }
            //     localStorage.openId = user.openId;
            //     sessionStorage.houseId = user.houseId;
            //     ajaxData.user = user;
            //     if (user.houseId) {
            //         ajax({
            //             type: "GET",
            //             data: {
            //                 houseId: user.houseId,
            //             },
            //             success: function (data) {
            //                 if (data.code == '200') {
            //                     sessionStorage.houseNum = data.data.houseNum
            //                 } else {
            //                     alert(data.desc);
            //                 }
            //             }
            //         }, lf.finger.api.household.getHouseInfo);
            //         ajax({
            //             type: 'get',
            //             data: {
            //                 projectId: user.projectId,
            //             },
            //             success: function (data) {
            //                 var images = [],
            //                     url = [],
            //                     imageContentIds = [],
            //                     titles = [];
                            
            //                 $.each(data.dataList, function () {
            //                     if (this.imagePosition && this.imagePosition != '2') {
            //                         images.push(this.imageUrl);
            //                         url.push(this.openUrl || '');
            //                         titles.push(this.title);
                                    
            //                         this.imageContent ? imageContentIds.push(this.id) : imageContentIds.push('');
            //                     }
            //                 });
                            
            //                 me.setState({
            //                     homeImages: images,
            //                     imgOpenUrl: url,
            //                     imageContentIds: imageContentIds,
            //                     titles: titles,
            //                 });
                            
            //             }
            //         }, lf.finger.api.homeImages);
            //     } else {
            //         me.setState({
            //             hasImg: false
            //         })
            //         console.log('user.userId is not defined');
            //     }
            // })
        },
        ready(user){
            var me = this;

            //查询设备
            queryAllDevice(function (deviceList) {
                me.setState({
                    hasQueryDevice: true,
                    iconList: me.renderIcon(fixedIcon.concat(deviceList))
                })
            });

            user.custLoginVo && user.custLoginVo.authModules.map((type, i) => {
                if (type == authModules.module.property) {
                    me.setState({
                        isProperty: true,
                    })
                }
            })
            if (!user.custLoginVo) { //兼容3.0以前的老版本
                me.setState({
                    isProperty: true,
                })
            }
            localStorage.openId = user.openId;
            sessionStorage.houseId = user.houseId;
            ajaxData.user = user;
            if (user.houseId) {
                ajax({
                    type: "GET",
                    data: {
                        houseId: user.houseId,
                    },
                    success: function (data) {
                        if (data.code == '200') {
                            sessionStorage.houseNum = data.data.houseNum
                        } else {
                            alert(data.desc);
                        }
                    }
                }, lf.finger.api.household.getHouseInfo);
                ajax({
                    type: 'get',
                    data: {
                        projectId: user.projectId,
                    },
                    success: function (data) {
                        var images = [],
                            url = [],
                            imageContentIds = [],
                            titles = [];
                        
                        $.each(data.dataList, function () {
                            if (this.imagePosition && this.imagePosition != '2') {
                                images.push(this.imageUrl);
                                url.push(this.openUrl || '');
                                titles.push(this.title);
                                
                                this.imageContent ? imageContentIds.push(this.id) : imageContentIds.push('');
                            }
                        });
                        
                        me.setState({
                            homeImages: images,
                            imgOpenUrl: url,
                            imageContentIds: imageContentIds,
                            titles: titles,
                        });
                        
                    }
                }, lf.finger.api.homeImages);
            } else {
                me.setState({
                    hasImg: false
                })
                console.log('user.userId is not defined');
            }
        },
        renderIcon: function (iconList) {
            let filterList = [], //筛选iconList
                count = 0;
            
            const add2FilterList = function (i, item) {
                if (item.deviceName.indexOf('帘') > -1) item.itemClass += ' iconfont curtain';
                //if (i == 2) item.itemClass = 'light3';
                //if (i == 3) item.itemClass = 'light4';
                //if(i == 4) item.itemClass = 'light2';
                //if(i == 5) item.itemClass = 'light1';
                
                //fixedIcon 是自带样式的
                if (!item.itemClass) {
                    item.itemClass = '';
                    
                    if (i > 21) //icon 最多到这里
                        i -= 21;
                    
                    if (i <= 8)
                        item.itemClass += ' purple';
                    item.itemClass += ' light' + i;
                }
                
                filterList.push(item)
            };
            
            //添加样式
            $.each(iconList, function (i, item) {
                //过虑健康设备
                if (item.type.indexOf('HEALTH') > -1) return;
                
                //显示子设备
                if (item.childDevices && item.childDevices.length > 0)
                    item.childDevices.map(item => add2FilterList(count++, item));
                else
                    add2FilterList(count++, item);
                
                
                //演示后打开
                //let name = item.name;
                //if(name.indexOf('灯') > -1){
                //    item.itemClass = 'light' + i;
                //    filterList.push(item);
                //}
                //else if(name.indexOf('窗帘') > -1 || name.indexOf('遥控') > -1){
                //    item.itemClass = 'purple light' + i;
                //    filterList.push(item);
                //}
                
            });
            
            
            //mui slier 每页装8个icon
            return lf.utils.to2DArray(filterList, 8).map(function (row) {
                return <FlexBox itemList={row}/>
            });
            
            
        },
        renderImgAndText: function (row) {
            var me = this,
                items = row.map(function (item) {
                    let fn;
                    
                    if (item.url) {
                        fn = () => lf.bridgeJs.doAction(item.url, item.pageTitle);
                    } else if (item.viewCode == viewCode.customerService) {
                        fn = function () {
                            ajax({
                                data: {
                                    projectId: ajaxData.user.projectId,
                                }
                            }, lf.finger.api.project, function (data) {
                                lf.bridgeJs.dial(data.tel);
                            })
                        }
                    } else {
                        fn = () => lf.bridgeJs.openNativeView(item.viewCode);
                    }
                    return <ImgAndText tapFn={fn} img={item.img} title={item.title} detail={item.detail}
                                       addClass="flex-item" titleClass={item.titleClass}/>
                });
            
            return (
                <div className="flex-box-row">
                    {items}
                </div>
            )
        },
        _homeImagesFn: function (node) {
            var $links = $(node).find('.mui-slider-item').not('.mui-slider-item-duplicate'),
                me = this;
            
            $links.each(function (i) {
                var $me = $(this);
                $me.off();
                $me.on('tap', function () {
                    var id = me.state.imageContentIds[i],
                        url = me.state.imgOpenUrl[i],
                        title = me.state.titles[i];
                    
                    if (id)
                        doAction('property-img-content.html?id=' + id, title);
                    else
                        doAction(url, title);
                });
            });
        },
        _showDeveloping() {
            this.setState({
                showDeveloping: true
            });
        },
        render: function () {
            var st = this.state,
                iconList = [];
            if (st.hasQueryDevice) iconList = st.iconList;
            else
                iconList = this.renderIcon(fixedIcon);
            
            //<Snowball/>
            // remove class => app-margin-bottom
            
            let imgDefault = ['../public/images/finger/banner-index.jpg', '../public/images/finger/banner-index.jpg'];
            return (
                <div ref="root" className="finger index">
                    {
                        this.state.isProperty || this.state.hasImg ?
                            <MuiSlider height={activity ? '' : "2.1"}
                                       addClass={activity ? 'home-img' : ''}
                                       imgList={st.homeImages}
                                       indicator="true"
                                       fn={this._homeImagesFn} autoPlay="true" loop={true}/>
                            :
                            <MuiSlider height={"2.1"} imgList={imgDefault}/>
                    }
                    {
                        this.state.isProperty ? <DevList /> : ''
                    }
                    <StableContent addClass="margin-top" showDeveloping={this._showDeveloping}/>
                    <i className="split-line"/>
                    {
                        <FlexBox rowRender={this.renderImgAndText}
                                 itemList={this.props.imgAndTextList}
                                 count="2"
                                 addClass="margin-top"/>
                    }
                    
                    <Developing show={this.state.showDeveloping}/>
                </div>
            )
        },
    });
    
    var DevList = RC({
        getInitialState() {
            return ({
                iconList: [],
                noItem: 'default',
                hasQueryDevice: false,
            })
            
        },
        componentDidMount() {
            let me = this;
            queryAllDevice(function (deviceList) {
                me.setState({
                    hasQueryDevice: true,
                    iconList: me.renderIcon(fixedIcon.concat(deviceList))
                })
            });
        },
        renderIcon: function (iconList) {
            let filterList = [], //筛选iconList
                count = 0;
            
            const add2FilterList = function (i, item) {
                if (item.deviceName.indexOf('帘') > -1) item.itemClass += ' iconfont curtain';
                //if (i == 2) item.itemClass = 'light3';
                //if (i == 3) item.itemClass = 'light4';
                //if(i == 4) item.itemClass = 'light2';
                //if(i == 5) item.itemClass = 'light1';
                
                //fixedIcon 是自带样式的
                if (!item.itemClass) {
                    item.itemClass = '';
                    
                    if (i > 21) //icon 最多到这里
                        i -= 21;
                    
                    if (i <= 8)
                        item.itemClass += ' purple';
                    item.itemClass += ' light' + i;
                }
                
                filterList.push(item)
            };
            
            //添加样式
            $.each(iconList, function (i, item) {
                //过虑健康设备
                if (item.type.indexOf('HEALTH') > -1) return;
                
                //显示子设备
                if (item.childDevices && item.childDevices.length > 0)
                    item.childDevices.map(item => add2FilterList(count++, item));
                else
                    add2FilterList(count++, item);
                
                
                //演示后打开
                //let name = item.name;
                //if(name.indexOf('灯') > -1){
                //    item.itemClass = 'light' + i;
                //    filterList.push(item);
                //}
                //else if(name.indexOf('窗帘') > -1 || name.indexOf('遥控') > -1){
                //    item.itemClass = 'purple light' + i;
                //    filterList.push(item);
                //}
                
            });
            
            //mui slier 每页装8个icon
            return lf.utils.to2DArray(filterList, 8).map(function (row) {
                return <FlexBox itemList={row}/>
            });
            
            
        },
        render() {
            var st = this.state,
                iconList = [];
            if (st.hasQueryDevice) iconList = st.iconList;
            else
                iconList = this.renderIcon(fixedIcon);
            
            return (
                <div>
                    <MuiSlider itemList={iconList} indicator="true"
                               addClass={ activity ? 'slider-activity' : "margin-top"}
                               noItem={st.noItem}/>
                </div>
            )
        }
        
    })
    
    r.render(
        <PullRefresh data={<Root imgAndTextList={imgAndTextList} />}/>,
        document.getElementById('root'),
        function () {
            //$('.finger')[0].style.webkitTransform = 'translateY(-.25rem)';
            $('.mui-scroll').css({
                background: '#f2f2f2'
            });
            $('.mui-content').css('background', "#f2f2f2");
        }
    )
    
})(liefeng, React)